package net.loyin.app.model;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import net.loyin.annotation.TableBind;
import net.loyin.app.model.base.BaseSysUser;

import java.util.ArrayList;
import java.util.List;

/***
 * 系统管理用户
 */
@TableBind(tableName = SysUser.tableName)
public class SysUser extends BaseSysUser<SysUser> {
	public static final String tableName="sys_user";
	public static SysUser dao=new SysUser();
	/**
	 * 登录
	 * @param username
	 * @param password 加密后
	 * @return
	 */
	public SysUser login(String username,String password){
		return this.findFirst("select * from sys_user where (account=? or email=?) and password=? and status=1 ",username,username,password);
	}

	/***
	 * 配置用户角色
	 * @param userid
	 * @param roles
     */
	@Before(Tx.class)
	public void cfgRole(String userid,String[] roles){
		Db.update("delete from sys_user_role where user_id=?",userid);
		if(roles!=null&&roles.length>0) {
			String[][]paras=new String[roles.length][2];
			for(int i=0;i<roles.length;i++){
				paras[i][0]=userid;
				paras[i][1]=roles[i];
			}
			Db.batch("insert into sys_user_role (user_id,role_id) values(?,?)", paras,10);
		}
	}

	/***
	 * 获取用户角色id
	 * @param userid
	 * @return
     */
	public List<String> qryUserRolesId(String userid){
		List<Record>list=Db.find("select role_id from sys_user_role where user_id=?",userid);
		List<String> roles=new ArrayList<String>();
		if(list!=null&&list.isEmpty()==false){
			for(Record r : list){
				roles.add(r.getStr("role_id"));
			}
		}
		return roles;
	}
	/***
	 * 获取用户角色
	 * @param userid
	 * @return
     */
	public List<SysRole> qryUserRoles(String userid){
		return SysRole.dao.find("select r.id,r.name from sys_role r,sys_user_role ur where r.id=ur.role_id and r.status=1 and ur.user_id=?",userid);
	}

	/**
	 * 校验师傅存在账号
	 * @param account
	 * @param userid
     * @return true 校验通过
     */
	public boolean checkAccount(String account, String userid) {
		SysUser entity=this.findFirst("select * from sys_user where account=? and id !=? ",account,userid);
		return entity==null;
	}

	/**
	 * 校验师傅存在邮箱
	 * @param email
	 * @param userid
     * @return true 校验通过
     */
	public boolean checkEmail(String email, String userid) {
		SysUser entity=this.findFirst("select * from sys_user where email=? and id !=? ",email,userid);
		return entity==null;
	}
}
